<template>
  <el-container>
    <el-header style="background: #fff; border: 1px #e9eef3 solid;">
      <h1 class="title">学生公寓分配管理系统——管理端</h1>
      <el-dropdown style="float: right; margin-top: 30px; margin-right: 50px; font-size: 20px;">
        <span class="el-dropdown-link">
          {{ admin.username }}
          <el-icon class="el-icon--right">
            <arrow-down/>
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-header>
    <el-container>'

      <!-- 左侧导航栏 -->
      <el-aside width="200px" style="height: 80%;">
        <el-menu default-active="/admin" router class="el-menu-vertical-demo" default-openeds="{1,2,3}">
          <el-sub-menu index="1">
            <template #title>
              <el-icon>
                <user/>
              </el-icon>
              <span>学生管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/admin">学生信息</el-menu-item>
              <el-menu-item index="/admin/apartment">宿舍分配</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
          <el-sub-menu index="2">
            <template #title>
              <el-icon>
                <grid/>
              </el-icon>
              <span>宿舍管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/admin/buildingInfo">楼栋信息</el-menu-item>
              <el-menu-item index="/admin/roomInfo">宿舍信息</el-menu-item>
              <el-menu-item index="/admin/bedInfo">床位信息</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
          <view v-if="admin.role==1">
            <el-sub-menu index="3">
              <template #title>
                <el-icon>
                  <stamp/>
                </el-icon>
                <span>人事管理</span>
              </template>
              <el-menu-item-group>
                <el-menu-item index="/admin/adminInfo">宿管信息</el-menu-item>
                <el-menu-item index="/admin/adminPermissions">宿管审核</el-menu-item>
              </el-menu-item-group>
            </el-sub-menu>
          </view>
        </el-menu>
      </el-aside>
      <!-- 右侧内容栏 -->
      <el-main style="background-color: #fff;">
        <el-table
            :data="tableData.slice((pagination.currentPage-1)*pagination.pageSize, pagination.currentPage*pagination.pageSize)"
            :default-sort="{ prop: 'sid', order: 'descending' }"
            style="width: 100%; padding: 8px 8px 0 8px;">
          <el-table-column prop="sid" label="学号" width="120"/>
          <el-table-column prop="name" label="姓名" width="120"/>
          <el-table-column prop="sex" label="性别" width="100" :formatter="formatSex"/>
          <el-table-column prop="major" label="专业" width="100"/>
          <el-table-column prop="classroom" label="班级" width="100"/>
          <el-table-column prop="cellphone" label="手机号码" width="130"/>
          <el-table-column prop="nation" label="民族" width="100"/>
          <el-table-column prop="buildingName" label="宿舍楼" width="100"/>
          <el-table-column prop="roomNum" label="宿舍号" width="100"/>
          <el-table-column prop="bedNum" label="床位号" width="100"/>
          <el-table-column prop="id" label="操作" width="180">
            <template #default="scope">
              <el-button size="small" type="success" plain @click="editStuDialog(scope.row.id)">编辑</el-button>
              <el-popconfirm title="确定删除该学生吗?" @confirm="deleteStu(scope.row.id)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <div class="footer">
          <!-- 添加学生按钮 -->
          <div class="addStuBtn">
            <el-button type="primary" plain @click="addStuDialog">添加学生</el-button>
            <!-- 导出Excel按钮 -->
            <el-button type="success" plain @click="exportData" >导出Excel</el-button>
          </div>
          <!-- 分页 -->
          <el-pagination background layout="prev, pager, next"
                         v-model:currentPage="pagination.currentPage"
                         :page-size="pagination.pageSize"
                         :total="pagination.total"
                         @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>

    <!-- 添加学生dialog -->
    <el-dialog
        v-model="dialogVisible" title="添加学生" width="50%">
      <el-form :label-position="left" label-width="10px;" :model="stu" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="学号" prop="sid">
              <el-input v-model="stu.sid" placeholder="请输入学号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="stu.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="stu.sex">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="民族" prop="nation">
              <el-input v-model="stu.nation" placeholder="请输入民族"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业" prop="major">
              <el-input v-model="stu.major" placeholder="请输入专业"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班级" prop="classroom">
              <el-input v-model="stu.classroom" placeholder="请输入班级"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="手机号码" prop="cellphone">
              <el-input v-model="stu.cellphone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-model="stu.password" placeholder="请输入密码" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col span="4" v-if="admin.role==2">
            <el-form-item label="宿舍楼">
              <el-input v-model="stu.buildingName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col span="4" v-else>
            <el-form-item label="宿舍楼" prop="buildingName">
              <el-select v-model="stu.buildingName" placeholder="选择宿舍楼">
                <el-option label="未分配" value="-1"></el-option>
                <el-option v-for="(item,index) in allBuilding" :key="index" :label="item.buildingName"
                           :value="item.buildingName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <span v-if="stu.buildingName=='-1'">
            <el-col span="4">
            <el-form-item label="宿舍号">
              <el-input v-model="stu.roomNum" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col span="4">
            <el-form-item label="床位号">
              <el-input v-model="stu.bedNum" disabled></el-input>
            </el-form-item>
          </el-col>
          </span>
          <span v-else>
            <el-col span="4">
            <el-form-item label="宿舍号">
              <el-input v-model="stu.roomNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="4">
            <el-form-item label="床位号">
              <el-input v-model="stu.bedNum"></el-input>
            </el-form-item>
          </el-col>
          </span>
        </el-row>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addStu">添加</el-button>
      </span>
      </template>
    </el-dialog>

    <!-- 编辑学生dialog -->
    <el-dialog
        v-model="editStuDialogVisible" title="编辑学生" width="50%">
      <el-form :label-position="left" label-width="10px;" :model="editStuInfo" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="学号" prop="sid">
              <el-input v-model="editStuInfo.sid" placeholder="请输入学号" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editStuInfo.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="editStuInfo.sex">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="民族" prop="nation">
              <el-input v-model="editStuInfo.nation" placeholder="请输入民族"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业" prop="major">
              <el-input v-model="editStuInfo.major" placeholder="请输入专业"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班级" prop="classroom">
              <el-input v-model="editStuInfo.classroom" placeholder="请输入班级"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="手机号码" prop="cellphone">
              <el-input v-model="editStuInfo.cellphone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-model="editStuInfo.password" placeholder="请输入密码" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col span="4" v-if="admin.role==2">
            <el-form-item label="宿舍楼">
              <el-input v-model="editStuInfo.buildingName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col span="4" v-else>
            <el-form-item label="宿舍楼" prop="buildingName">
              <el-select v-model="editStuInfo.buildingName" placeholder="选择宿舍楼">
                <el-option label="未分配" value="-1"></el-option>
                <el-option v-for="(item,index) in allBuilding" :key="index" :label="item.buildingName"
                           :value="item.buildingName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <span v-if="editStuInfo.buildingName=='-1'">
            <el-col span="4">
            <el-form-item label="宿舍号">
              <el-input v-model="editStuInfo.roomNum" disabled model-value=""></el-input>
            </el-form-item>
          </el-col>
          <el-col span="4">
            <el-form-item label="床位号">
              <el-input v-model="editStuInfo.bedNum" disabled model-value=""></el-input>
            </el-form-item>
          </el-col>
          </span>
          <span v-else>
            <el-col span="4">
            <el-form-item label="宿舍号">
              <el-input v-model="editStuInfo.roomNum" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="4">
            <el-form-item label="床位号">
              <el-input v-model="editStuInfo.bedNum" type="number"></el-input>
            </el-form-item>
          </el-col>
          </span>
        </el-row>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="editStuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editStu">修改</el-button>
      </span>
      </template>
    </el-dialog>
  </el-container>


</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import {Stamp, User, Grid, ArrowDown} from '@element-plus/icons'
import axios from 'axios'
import XLSX from 'xlsx'

export default {
  data() {
    return {
      editStuInfo: {
        id: null,
        sid: '',
        name: '',
        sex: '0',
        nation: '',
        major: '',
        classroom: '',
        cellphone: '',
        password: '',
        buildingId: '',
        buildingName: '',
        roomId: '',
        roomNum: {
          type: Number
        },
        bedId: '',
        bedNum: {
          type: Number
        }
      },
      editStuDialogVisible: false,
      rules: {
        sid: [{
          required: true,
          message: '请输入学号',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '请选择性别',
          trigger: 'blur'
        }],
        nation: [{
          required: true,
          message: '请输入民族',
          trigger: 'blur'
        }],
        major: [{
          required: true,
          message: '请输入专业',
          trigger: 'blur'
        }],
        classroom: [{
          required: true,
          message: '请输入班级',
          trigger: 'blur'
        }],
        cellphone: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        buildingName: [{
          required: true,
          message: '请输入学号',
          trigger: 'blur'
        }],
      },
      allBuilding: [],
      pagination: {
        total: {
          type: Number
        },
        currentPage: 1,
        pageSize: 8
      },
      dialogVisible: false,
      admin: {
        username: '',
        role: '',
        buildingName: ' '
      },
      tableData: [],
      stu: {
        sid: '',
        name: '',
        sex: '0',
        nation: '',
        major: '',
        classroom: '',
        cellphone: '',
        password: '',
        buildingId: '',
        buildingName: '',
        roomId: '',
        roomNum: '',
        bedId: '',
        bedNum: ''
      }
    }
  },

  methods: {
    /*
      通过xlsx插件导出数据到excel
     */
    exportData() {
      let excelData = [
          // 表头
          ['学号', '姓名', '性别', '专业', '班级', '手机号码', '民族', '宿舍楼', '宿舍号', '床位号']
      ]

      this.tableData.forEach(item => {
          let rowData = [];
          let gender;
          if (item.sex == '0') {
            gender = '男';
          } else if (item.sex == '1') {
            gender = '女';
          }
          rowData = [
              item.sid,
              item.name,
              gender,
              item.major,
              item.classroom,
              item.cellphone,
              item.nation,
              item.buildingName,
              item.roomNum,
              item.bedNum
          ]
          excelData.push(rowData);
      })
      let ws = XLSX.utils.aoa_to_sheet(excelData);
      let wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '学生公寓信息');
      XLSX.writeFile(wb, '学生公寓分配管理系统.xlsx');
    },

    /*
      编辑学生dialog
     */
    editStuDialog(id) {
      this.editStuDialogVisible = true;

      // 封装请求数据
      let selectId = new URLSearchParams();
      selectId.append('id', id);

      const _this = this.$data;

      // 通过aixos发送请求
      axios.post("/stu/selectById", selectId)
        .then(function(res) {
          _this.editStuInfo = res.data.data;
          console.log(_this.editStuInfo)
          if (!res.data.data.buildingName) {
            _this.editStuInfo.buildingName = "-1";
          }
          // 将sex 从Integer转为String才能正常渲染
          _this.editStuInfo.sex = "" + res.data.data.sex;
        })
    },


    /*
      删除学生
     */
    deleteStu(id) {

      // 封装请求数据
      let delStuData = new URLSearchParams();
      delStuData.append('id', id);

      // 发送axios请求删除学生
      axios.post("/stu/delStu", delStuData)
          .then(function (res) {
            console.log(res)
            switch (res.data.status) {
              case 10000:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '删除成功！',
                  type: 'success',
                })
                // 刷新页面
                location.reload();
                break;
              case 10008:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '权限不够！',
                  type: 'error',
                })
                break;
            }
          })
    },

    /*
       将后端传来性别的0，1转为男女给table
     */
    formatSex(row, column, cellValue) {
      if (cellValue == 0) {
        return '男'
      } else if (cellValue == 1) {
        return '女'
      }
    },

    /*
        退出登录
     */
    logout() {

      // 删除后端session
      axios.get("/admin/logout")
          .then(function(res) {
            console.log(res)
          })

      // 清除sessionStorage
      sessionStorage.clear();

      // 弹出提示窗口
      ElMessage({
        showClose: true,
        message: '账号已退出！',
        type: 'success',
      })

      // 跳转到登录页面
      this.$router.push("/admin/login");
    },

    /*
      新增学生弹框
     */
    addStuDialog() {
      this.dialogVisible = true;
    },
    /*
      新增学生操作
     */
    addStu() {
      // 判断信息是否填了
      if (!this.stu.sid || !this.stu.name || !this.stu.nation || !this.stu.major || !this.stu.classroom ||
          !this.stu.cellphone || !this.stu.password || !this.stu.buildingName) {
        // 弹出提示窗口
        ElMessage({
          showClose: true,
          message: '学生信息不能为空',
          type: 'error',
        })
        return;
      }
      // 用URLSearchParams封装请求参数
      let addStuData = new URLSearchParams();
      addStuData.append('sid', this.stu.sid);
      addStuData.append('name', this.stu.name);
      addStuData.append('sex', this.stu.sex);
      addStuData.append('nation', this.stu.nation);
      addStuData.append('major', this.stu.major);
      addStuData.append('classroom', this.stu.classroom);
      addStuData.append('password', this.stu.password);
      addStuData.append('cellphone', this.stu.cellphone);
      addStuData.append('buildingName', this.stu.buildingName);
      addStuData.append('roomNum', this.stu.roomNum);
      addStuData.append('bedNum', this.stu.bedNum);

      const _this = this.$data;
      // 进行axios请求
      axios.post("/stu/addStu", addStuData)
          .then(function (res) {
            console.log(res.data.status)
            switch (res.data.status) {
              case 10000 :
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '添加成功',
                  type: 'success',
                })
                _this.dialogVisible = false;
                location.reload();
                break;
              case 10023:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '宿舍楼不存在',
                  type: 'error',
                })
                break;
              case 10030:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '宿舍不存在',
                  type: 'error',
                })
                break;
              case 10033:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '床位不存在',
                  type: 'error',
                })
                break;
              case 10041:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '床位已有人住',
                  type: 'error',
                })
                break;
              case 10050:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '学号已存在',
                  type: 'error',
                })
                break;
            }
          })

      console.log(this.stu)
    },

    /*
      编辑学生操作
     */
    editStu() {
      // 判断信息是否填了
      if (!this.editStuInfo.sid || !this.editStuInfo.name || !this.editStuInfo.nation || !this.editStuInfo.major || !this.editStuInfo.classroom ||
          !this.editStuInfo.cellphone || !this.editStuInfo.password || !this.editStuInfo.buildingName) {
        // 弹出提示窗口
        ElMessage({
          showClose: true,
          message: '学生信息不能为空',
          type: 'error',
        })
        return;
      }
      // 用URLSearchParams封装请求参数
      let editStuData = new URLSearchParams();
      editStuData.append('id', this.editStuInfo.id)
      editStuData.append('sid', this.editStuInfo.sid);
      editStuData.append('name', this.editStuInfo.name);
      editStuData.append('sex', this.editStuInfo.sex);
      editStuData.append('nation', this.editStuInfo.nation);
      editStuData.append('major', this.editStuInfo.major);
      editStuData.append('classroom', this.editStuInfo.classroom);
      editStuData.append('cellphone', this.editStuInfo.cellphone);
      editStuData.append('password', this.editStuInfo.password);
      editStuData.append('buildingName', this.editStuInfo.buildingName);

      // 解决传到后端数据类型错误的问题
      if (!this.editStuInfo.roomNum) {
        editStuData.append('roomNum', -1);
      } else {
        editStuData.append('roomNum', this.editStuInfo.roomNum);
      }
      if (!this.editStuInfo.bedNum) {
        editStuData.append('bedNum', -1);
      } else {
        editStuData.append('bedNum', this.editStuInfo.bedNum);
      }

      const _this = this.$data;
      // 进行axios请求
      axios.post("/stu/editStu", editStuData)
          .then(function (res) {
            console.log(res.data)
            switch (res.data.status) {
              case 10000 :
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '修改成功',
                  type: 'success',
                })
                _this.editStuDialogVisible = false;
                // 刷新页面
                location.reload();
                break;
              case 10023:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '宿舍楼不存在',
                  type: 'error',
                })
                break;
              case 10030:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '宿舍不存在',
                  type: 'error',
                })
                break;
              case 10033:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '床位不存在',
                  type: 'error',
                })
                break;
              case 10041:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '床位已有人住',
                  type: 'error',
                })
                break;
              case 10050:
                // 弹出提示窗口
                ElMessage({
                  showClose: true,
                  message: '学号已存在',
                  type: 'error',
                })
                break;
            }
          })

    },
    /*
        更改当前页
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    }
  },

  mounted() {
    // 判断用户是否已经登录
    if (!sessionStorage.getItem('username')) {
      // 弹出提示窗口
      ElMessage({
        showClose: true,
        message: '请登录！',
        type: 'error',
      })
      // 路由跳转
      this.$router.push('/admin/login');
      return;
    }

    // 从sessionStorage获取用户名，赋值给data
    this.admin.username = sessionStorage.getItem("username");
    this.admin.role = sessionStorage.getItem("role");
    if (this.admin.role == 2) {
      this.admin.buildingName = sessionStorage.getItem("buildingName");
      this.stu.buildingName = sessionStorage.getItem("buildingName");
    }


    let that = this.$router;
    var _this = this.$data;
    // 通过axios查询学生信息
    axios.post('/stu/select')
        .then(function (res) {
          if (res.data.status == 10014) {
            // 弹出提示窗口
            ElMessage({
              showClose: true,
              message: '未登录，请重新登录！',
              type: 'error',
            })
            // 路由跳转
            that.push('/admin/login');
            return;
          }
          console.log(res.data.data)
          _this.tableData = res.data.data;
          _this.pagination.total = res.data.data.length
        })

    /*
      获取所有宿舍楼信息
     */
    axios.post('/admin/building/select')
        .then(function (res) {
          _this.allBuilding = res.data.data
        })
  },

  components: {
    Stamp,
    User,
    Grid,
    ArrowDown
  }
}
</script>

<style scoped>
.el-header, .el-footer {
  background-color: #b3c0d1;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #d3dce6;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 200px;
}

.el-main {
  background-color: #e9eef3;
  color: var(--el-text-color-primary);
  text-align: center;
  margin: 0px;
  padding: 0px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-header {
  width: 100%;
  height: 80px;
  display: block;
  line-height: 80px;
  padding-left: 50px;
}

.el-header .title {
  font-size: 20px;
  float: left;
  color: #303133;
}

.addStuBtn .el-button {
  float: left;
  margin: 10px 100px 10px 10px;
}

.footer .el-pagination {
  float: right;
  margin: 20px 30px 10px 10px;
}
</style>